import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { Card, Tabs, Form, Input, Button, Avatar, message, Spin, Divider, Radio, Upload } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined, HomeOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import type { RcFile } from 'antd/es/upload/interface';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getUserProfile, uploadAvatar, changePassword } from '../../../api/userApi';
import { setUser } from '../../../store/features/userSlice';
import { useCurrentUser } from '../../../hooks/authHooks';
import { STORAGE_KEYS } from '../../../constants/common';
import './UserProfile.scss';

// API基础URL，应该从配置文件导入，这里直接定义
const API_BASE_URL = process.env.REACT_APP_API_URL || '/adminapi';

// 用于缓存已加载头像URL的Map，避免重复请求
const avatarUrlCache = new Map<string, string>();

const { TabPane } = Tabs;
const { TextArea } = Input;

// 用户信息表单类型
interface UserProfileForm {
  username: string;
  region: string;
  email?: string;
  phone?: string;
  location?: string;
  introduction?: string;
  gender?: number;
}

// 密码表单类型
interface PasswordForm {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const UserProfile: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>('profile');
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [form] = Form.useForm<UserProfileForm>();
  const [passwordForm] = Form.useForm<PasswordForm>();
  const queryClient = useQueryClient();
  const dispatch = useDispatch();
  const { userInfo } = useCurrentUser();
  const [loading, setLoading] = useState<boolean>(false);

  // 确保userInfo有默认值，避免null错误
  const username = userInfo?.username || '';
  const userRole = userInfo?.role?.roleName || '未知角色';
  const userRegion = userInfo?.region || '总部';

  // 获取头像URL的辅助函数 - 修改版本，添加认证令牌
  const getAvatarUrl = (url?: string, username?: string) => {
    // 如果没有URL，使用默认头像服务
    if (!url) {
      return `https://api.dicebear.com/7.x/miniavs/svg?seed=${username || ''}`;
    }
    
    // 检查缓存中是否已有此URL
    const cacheKey = url;
    if (avatarUrlCache.has(cacheKey)) {
      return avatarUrlCache.get(cacheKey) as string;
    }
    
    // 已经是完整URL的情况
    if (url.startsWith('http')) {
      avatarUrlCache.set(cacheKey, url);
      return url;
    }
    
    // 获取认证令牌，移除Bearer前缀
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
    const tokenValue = token ? token.replace('Bearer ', '') : '';
    
    // 确保路径开头有斜杠
    let path = url.startsWith('/') ? url : `/${url}`;
    
    // 处理不同格式的路径
    // 如果路径中不包含avataruploads和uploads，添加avataruploads前缀
    if (!path.includes('/avataruploads/') && !path.includes('/uploads/')) {
      path = `/avataruploads${path}`;
    }
    
    // 构建带认证令牌的完整URL
    const baseUrl = `${API_BASE_URL}${path}`;
    
    // 添加token作为查询参数，确保后端可以识别
    const finalUrl = tokenValue ? `${baseUrl}?token=${encodeURIComponent(tokenValue)}` : baseUrl;
    
    // 存入缓存
    avatarUrlCache.set(cacheKey, finalUrl);
    
    return finalUrl;
  };

  // 获取用户详细信息
  const { isLoading } = useQuery({
    queryKey: ['userProfile'],
    queryFn: async () => {
      try {
        // 使用API获取用户资料
        const response = await getUserProfile();
        
        // 减少不必要的日志输出
        if (process.env.NODE_ENV === 'development') {
          console.log('用户资料:', response);
        }
        
        const userData = response;
      
        // 更新表单数据
        form.setFieldsValue({
          username: userData.username,
          region: userData.region,
          email: userData.email || '',
          phone: userData.phone || '',
          location: userData.location || '',
          introduction: userData.introduction || '',
          gender: userData.gender || 0
        });

        // 更新头像
        if (userData.avatar) {
          setAvatarUrl(getAvatarUrl(userData.avatar));
          console.log('用户资料中的头像URL:', getAvatarUrl(userData.avatar));
        }
      
        return userData;
      } catch (error) {
        console.error('获取用户资料失败:', error);
        throw error;
      }
    },
    // 减少不必要的查询
    staleTime: 1000 * 60 * 5, // 5分钟内不重新获取
    refetchOnWindowFocus: false, // 窗口聚焦时不重新获取
    refetchOnMount: 'always' // 组件挂载时始终获取
  });

  // 更新用户信息
  const updateUserMutation = useMutation({
    mutationFn: async (data: UserProfileForm) => {
      // 检查是否已登录并有有效令牌
      const storedToken = localStorage.getItem(STORAGE_KEYS.TOKEN);
      if (!storedToken) {
        console.error('未找到认证令牌');
        throw new Error('未找到认证令牌，请重新登录');
      }
      
      console.log('开始更新用户信息，认证令牌存在');
      
      // 创建FormData对象
      const formData = new FormData();
      
      // 添加所有字段
      Object.keys(data).forEach(key => {
        if (data[key as keyof UserProfileForm] !== undefined && key !== 'username') {
          formData.append(key, String(data[key as keyof UserProfileForm]));
        }
      });
      
      // 使用上传API，因为它处理所有字段
      const result = await uploadAvatar(formData);
      console.log('更新返回结果:', result);
      return result;
    },
    onSuccess: (userData) => {
      // 只显示一次成功消息
      message.success('个人信息更新成功');
      
      // 不在reducer执行期间调用dispatch
      setTimeout(() => {
        try {
          // 更新Redux状态
          if (userData) {
            dispatch(setUser(userData));
            
            // 同步更新localStorage中的用户信息 - 使用单独的try/catch隔离可能的错误
            try {
              const storedUserStr = localStorage.getItem('userInfo');
              if (storedUserStr) {
                const storedUser = JSON.parse(storedUserStr);
                // 合并新的用户信息
                const updatedUser = {
                  ...storedUser,
                  ...userData
                };
                localStorage.setItem('userInfo', JSON.stringify(updatedUser));
              }
            } catch (error) {
              console.error('更新localStorage时出错:', error);
            }
          }
          
          // 更新用户信息缓存
          queryClient.invalidateQueries({ queryKey: ['userProfile'] });
        } catch (error) {
          console.error('更新用户状态时出错:', error);
          // 不显示错误消息，避免混淆用户
        }
      }, 0);
    },
    onError: (error) => {
      message.error(`更新失败：${error instanceof Error ? error.message : '未知错误'}`);
    }
  });

  // 修改密码
  const changePasswordMutation = useMutation({
    mutationFn: async (data: { oldPassword: string; newPassword: string }) => {
      // 检查是否已登录并有有效令牌
      const storedToken = localStorage.getItem(STORAGE_KEYS.TOKEN);
      if (!storedToken) {
        console.error('未找到认证令牌');
        throw new Error('未找到认证令牌，请重新登录');
      }
      
      console.log('开始修改密码，认证令牌存在');
      return changePassword(data.oldPassword, data.newPassword);
    },
    onSuccess: () => {
      message.success('密码修改成功');
      passwordForm.resetFields();
    },
    onError: (error) => {
      console.error('密码修改详细错误:', error);
      let errorMessage = '密码修改失败';
      
      if (error instanceof Error) {
        errorMessage = `密码修改失败：${error.message}`;
        
        // 检查是否是认证错误
        if (error.message.includes('401') || error.message.includes('未认证') || error.message.includes('认证令牌')) {
          errorMessage = '认证已过期，请重新登录';
        }
      }
      
      message.error(errorMessage);
    }
  });

  // 上传头像 - 简化版本
  const uploadAvatarMutation = useMutation({
    mutationFn: async (file: RcFile) => {
      setLoading(true);
      
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', file);
      
      // 检查是否已登录并有有效令牌
      const storedToken = localStorage.getItem(STORAGE_KEYS.TOKEN);
      if (!storedToken) {
        console.error('未找到认证令牌');
        throw new Error('未找到认证令牌，请重新登录');
      }
      
      console.log('开始上传头像，认证令牌存在');
      return await uploadAvatar(formData);
    },
    onSuccess: (userData) => {
      setLoading(false);
      message.success('头像上传成功');
      
      // 更新头像URL
      if (userData?.avatar) {
        const newAvatarUrl = getAvatarUrl(userData.avatar);
        setAvatarUrl(newAvatarUrl);
        console.log('头像上传成功，新URL:', newAvatarUrl);
      } else {
        console.warn('头像上传成功但没有返回avatar字段');
      }
      
      // 延迟更新Redux状态，避免在reducer执行期间调用
      setTimeout(() => {
        try {
          // 更新Redux状态
          if (userData) {
            dispatch(setUser(userData));
            
            // 同步更新localStorage中的用户信息
            try {
              const storedUserStr = localStorage.getItem('userInfo');
              if (storedUserStr) {
                const storedUser = JSON.parse(storedUserStr);
                // 合并新的用户信息，重点是头像
                const updatedUser = {
                  ...storedUser,
                  ...userData
                };
                localStorage.setItem('userInfo', JSON.stringify(updatedUser));
              }
            } catch (error) {
              console.error('更新localStorage时出错:', error);
            }
          }
          
          // 更新用户信息缓存
          queryClient.invalidateQueries({ queryKey: ['userProfile'] });
        } catch (error) {
          console.error('更新用户状态时出错:', error);
        }
      }, 0);
    },
    onError: (error) => {
      setLoading(false);
      console.error('头像上传详细错误:', error);
      let errorMessage = '头像上传失败';
      
      if (error instanceof Error) {
        errorMessage = `头像上传失败：${error.message}`;
        
        // 检查是否是认证错误
        if (error.message.includes('401') || error.message.includes('未认证') || error.message.includes('认证令牌')) {
          errorMessage = '认证已过期，请重新登录';
          // 可以考虑自动跳转到登录页
          // setTimeout(() => window.location.href = '/login', 1500);
        }
      }
      
      message.error(errorMessage);
    }
  });

  // 处理个人信息提交
  const handleProfileSubmit = (values: UserProfileForm) => {
    updateUserMutation.mutate(values);
  };

  // 处理密码修改提交
  const handlePasswordSubmit = (values: PasswordForm) => {
    const { oldPassword, newPassword } = values;
    changePasswordMutation.mutate({ oldPassword, newPassword });
  };

  // 处理头像上传前的校验
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('您只能上传JPG/PNG格式的图片!');
      return Upload.LIST_IGNORE;
    }
    
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于2MB!');
      return Upload.LIST_IGNORE;
    }
    
    // 直接上传文件
    uploadAvatarMutation.mutate(file);
    return false; // 阻止默认上传行为
  };

  // 处理头像加载错误
  const handleAvatarError = () => {
    // 防止循环：检查当前头像URL是否已经是备用头像
    if (avatarUrl && avatarUrl.includes('dicebear.com')) {
      return true; // 已经是备用头像，不再处理
    }
    
    console.error('头像加载失败，使用备用头像');
    
    // 直接使用默认头像服务生成的URL，不再尝试加载原始URL
    const defaultAvatarUrl = `https://api.dicebear.com/7.x/miniavs/svg?seed=${username || 'default'}`;
    setAvatarUrl(defaultAvatarUrl);
    
    return true; // 阻止继续尝试加载错误的URL
  };

  // 上传按钮
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  return (
    <div className="user-profile-container">
      <Card 
        title={<h2 className="profile-title">个人中心</h2>}
        className="profile-card"
      >
        <Spin spinning={isLoading}>
          <div className="user-profile-header">
            <div className="avatar-section">
              <Upload
                name="avatar"
                listType="picture-circle"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
              >
                {avatarUrl ? (
                  <Avatar 
                    size={100} 
                    src={avatarUrl}
                    className="user-avatar"
                    alt={username}
                    onError={handleAvatarError}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
              <div className="user-info">
                <h3>{username}</h3>
                <p>{userRole}</p>
                <p>{userRegion}</p>
              </div>
            </div>
          </div>

          <Divider />

          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            className="profile-tabs"
          >
            <TabPane tab="个人信息" key="profile">
              <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                onFinish={handleProfileSubmit}
              >
                {/* 用户名 */}
                <Form.Item 
                  label="用户名" 
                  name="username"
                  rules={[{ required: true, message: '请输入用户名' }]}
                >
                  <Input prefix={<UserOutlined />} placeholder="用户名" disabled />
                </Form.Item>
                
                {/* 区域 */}
                <Form.Item 
                  label="区域" 
                  name="region"
                >
                  <Input prefix={<HomeOutlined />} placeholder="区域" />
                </Form.Item>
                
                {/* 个人介绍 */}
                <Form.Item 
                  label="个人介绍" 
                  name="introduction"
                >
                  <TextArea 
                    placeholder="请输入个人介绍" 
                    autoSize={{ minRows: 3, maxRows: 6 }}
                  />
                </Form.Item>
                
                {/* 性别 */}
                <Form.Item 
                  label="性别" 
                  name="gender"
                >
                  <Radio.Group>
                    <Radio value={1}>男</Radio>
                    <Radio value={2}>女</Radio>
                    <Radio value={0}>未设置</Radio>
                  </Radio.Group>
                </Form.Item>
                
                {/* 邮箱 */}
                <Form.Item 
                  label="邮箱" 
                  name="email"
                  rules={[
                    { type: 'email', message: '邮箱格式不正确' }
                  ]}
                >
                  <Input prefix={<MailOutlined />} placeholder="邮箱" />
                </Form.Item>
                
                {/* 手机 */}
                <Form.Item 
                  label="手机" 
                  name="phone"
                >
                  <Input prefix={<PhoneOutlined />} placeholder="手机号码" />
                </Form.Item>
                
                {/* 地址 */}
                <Form.Item 
                  label="地址" 
                  name="location"
                >
                  <Input prefix={<HomeOutlined />} placeholder="地址" />
                </Form.Item>
                
                <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={updateUserMutation.isPending}
                  >
                    保存修改
                  </Button>
                </Form.Item>
              </Form>
            </TabPane>
            
            <TabPane tab="修改密码" key="password">
              <Form
                form={passwordForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                onFinish={handlePasswordSubmit}
              >
                {/* 旧密码 */}
                <Form.Item 
                  label="旧密码" 
                  name="oldPassword"
                  rules={[{ required: true, message: '请输入旧密码' }]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="旧密码" />
                </Form.Item>
                
                {/* 新密码 */}
                <Form.Item 
                  label="新密码" 
                  name="newPassword"
                  rules={[
                    { required: true, message: '请输入新密码' },
                    { min: 6, message: '密码至少6位字符' }
                  ]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
                </Form.Item>
                
                {/* 确认密码 */}
                <Form.Item 
                  label="确认密码" 
                  name="confirmPassword"
                  dependencies={['newPassword']}
                  rules={[
                    { required: true, message: '请确认密码' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'));
                      },
                    }),
                  ]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
                </Form.Item>
                
                <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={changePasswordMutation.isPending}
                  >
                    修改密码
                  </Button>
                </Form.Item>
              </Form>
            </TabPane>
          </Tabs>
        </Spin>
      </Card>
    </div>
  );
};

export default UserProfile; 